'''
Created on 2012-12-9

@author: xmxjq
'''

import sys, os
import mysql.connector
import datetime

def request_ajax_url(url,data,referer=None,**headers):
    import json
    import urllib
    import urllib2
    req = urllib2.Request(url)
    req.add_header('Content-Type', 'application/json')
    req.add_header('X-Requested-With','XMLHttpRequest')
    if referer:
        req.add_header('Referer',referer)
    if headers:
        for k in headers.keys():
            req.add_header(k,headers[k])
    postBody = json.dumps(data)

    response = urllib2.urlopen(req, postBody)
    return response.read()

def get_filename(url):  
    if url==None: return None  
    if url=="" : return ""  
    arr=url.split("/")  
    return arr[len(arr)-1] 

if __name__ == '__main__':
    now = datetime.datetime.now()

    from config import Config
    db = mysql.connector.Connect(**Config.dbinfo())
    cursor = db.cursor()
    stmt = "SELECT post_id, repost_num, post_time, display FROM post"
    stmt_like = "SELECT SUM(photo_like) FROM post_photo GROUP BY post_id HAVING post_id=%s"
    cursor.execute(stmt)
    update_list = []
    result = cursor.fetchall();
    for row in result:
        gravity = (now - row[2]).days
        if gravity <= 1:
            gravity = 1
        cursor.execute(stmt_like, (row[0],))
        like_result = cursor.fetchone()
        if like_result is None:
            like_result = [0,]
        if row[3] == 1:
            post_value = (row[1]*0.618 + float(like_result[0])*0.382) / gravity
        else:
            post_value = -1
        update_list.append(( post_value, like_result[0], row[0]))
    stmt_update = "UPDATE post SET post_value=%s, post_like=%s WHERE post_id=%s"    
    print tuple(update_list)
    cursor.executemany(stmt_update, tuple(update_list))
    db.commit()
    
    stmt = "SELECT post_id, post_value FROM post order by post_value DESC LIMIT 10"    
    stmt_photo = "SELECT a.photo_id, b.location FROM post_photo AS a INNER JOIN photo AS b ON a.photo_id = b.photo_id WHERE a.post_id=%s"
    stmt_delete = "DELETE FROM post_top_ten_index"
    stmt_insert = "INSERT INTO post_top_ten_index VALUES ( %s, %s, %s, %s )"
    cursor.execute(stmt)
    topten_list = []
    count_result = cursor.fetchall();
    for (offset, row) in enumerate(count_result):
        cursor.execute(stmt_photo, (row[0],))
        first_photo = cursor.fetchone()
        if first_photo is not None:
            import json
            response = request_ajax_url( Config.base_url()+"main/generate_top_ten_thumb/"+get_filename(first_photo[1]), None )
            result = json.loads(response)
            topten_list.append((offset+1, row[0], first_photo[0], result.get( 'path', None )))
        else:
            topten_list.append((offset+1, row[0], None, None))
    print topten_list
    cursor.execute(stmt_delete)
    cursor.executemany(stmt_insert, tuple(topten_list))
    
    db.commit()
    cursor.close()
    db.close()